const Schema =think.Mongoose.Schema;

module.exports  = class extends think.Mongoose {
    get schema() {
        const schema = new Schema({
            key: {
                type: String,
                required: true
            },
            title: {
                type: String,
                required: true
            },
            value: String,
            valueType: {type: String, default: 'String'},//值的类型:枚举，字符串，数值
            group: {type: Number, default: 0},//配置分组
            extra: String,
            remark: {
                type: String,
                default: ''
            },
            status: {
                type: Number,
                default: 1
            },
            sort: {type: Number, default: 0},
            deletable: {type: Boolean, default: true},
            editable: {type: Boolean, default: true},
        }, {timestamps: {}, minimize: false});



        /**
         * 设置或者读取系统配置项目的值
         * @param key
         * @param value
         * @returns {Promise<void>}
         * @constructor
         */
        schema.statics.C = async function (key, value) {

            //需要增加缓存提高性能
            if (typeof key === "undefined") {
                // think.logger.error(`必须指定key属性`);
                // throw new Error(`必须指定key属性`);
                //返回以下格式的JSON数组
                //[{ _id: 5aa0101e90d4ad39a8872a34, key: 'LIST_ROWS', value: '20' }]
                return this.find({},'key value').lean().exec();
            }

            if (typeof value === "undefined") {
                const row = await this.findOne({key: key.toUpperCase()}).exec();
                if (row) {
                    // think.logger.debug(`C[${key}]= ${row.value}`);
                    return row.value;
                } else {
                    // think.logger.error(`Key : ${key} 的配置项目不存在`);
                    throw new Error(`Key : ${key} 的配置项目不存在`);
                }

            } else {
                const row = await this.findOne({key: key.toUpperCase()}).exec();
                if (row) { //更新
                    if (row.editable) {
                        row.value = value;
                        await row.save();
                    } else {
                        // think.logger.error(`Key : ${key} 的配置项目不允许更改`);
                        throw new Error(`Key : ${key} 的配置项目不允许更改`);
                    }
                } else { //add new item
                    await this.create({key: key, value: value});
                }
            }
        }

        schema.set('toJSON', { virtuals: true });
        schema.set('toObject', { virtuals: true });

        return schema;
    }
};